package com.xinyue.game.center.business.account.logic;

import com.xinyue.game.center.common.ServerErrorCode;
import com.xinyue.game.center.dao.AccountDao;
import com.xinyue.game.center.dao.entity.AccountEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author 王广帅
 * @Date 2021/4/29 0:31
 */
@Service
public class AccountRegisterService {
    private Logger logger = LoggerFactory.getLogger(AccountRegisterService.class);
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AccountManager accountManager;
    @Autowired
    private AccountRedisManager accountRedisManager;

    public void accountRegister(AccountEntity account) {
        accountManager.checkUsername(account.getUsername());
        accountManager.checkPassword(account.getPassword());
        checkUsernameHaveRegister(account.getUsername());
        boolean saveResult = accountRedisManager.saveUsername(account.getUsername());
        if (saveResult) {
            AccountEntity saveAccount = accountDao.save(account);
            account.setId(saveAccount.getId());
            logger.info("用户注册成功,username:{}", account.getUsername());
        } else {
            throw ServerErrorCode.ACCOUNT_1005.exception();
        }
    }

    private void checkUsernameHaveRegister(String username) {
        AccountEntity account = accountDao.findByUsername(username);
        if (account != null) {
            throw ServerErrorCode.ACCOUNT_1005.exception();
        }
    }

}
